var express = require("express");
var router = express.Router();
const multer = require('multer');
var COS = require('cos-nodejs-sdk-v5');
const fs = require('fs');
const path = require('path');
const multiparty = require('multiparty')

const { cateModel, listModel, userModel, dingModel, lunboModel, } = require('../model/model')

router.get('/getlist', async (req, res) => {
  let { page, pageSize } = req.query

  let data = await listModel.find().skip((page - 1) * pageSize).limit(pageSize * 1)
  res.send({
    code: 200,
    data
  })
})

router.get('/getcate', async (req, res) => {
  let data = await cateModel.find()
  res.send({
    code: 200,
    data
  })
})

router.get('/getuser', async (req, res) => {
  let data = await userModel.find({ _id: "672ac6774d7ad220ec1d2d0f" })
  res.send({
    code: 200,
    data
  })
})

router.get('/getding', async (req, res) => {
  let data = await dingModel.find()
  res.send({
    code: 200,
    data
  })
})

router.get('/getlunbo', async (req, res) => {
  let data = await lunboModel.find()
  res.send({
    code: 200,
    data
  })
})


// 图片审核1
router.post('/shen', async (req, res) => {
  // 从请求体中获取 url 和 file 属性
  let { url, file } = req.body;
  // 创建一个 COS 对象，传入腾讯云的 SecretId 和 SecretKey，用于访问腾讯云对象存储服务
  const cos = new COS({
    SecretId: 'AKID43EH8kM1YwIzUvDG6lBMPq2AAvRijUDo',
    SecretKey: 'ThgRzIEyjOo0zmKfqqdEeqrfFblhQB1o',
  });
  // 配置对象存储的信息，包括存储桶名称和地域
  const config = {
    // 需要替换成您自己的存储桶信息
    Bucket: '3065060034-1326451460', // 存储桶，必须
    Region: 'ap-beijing', // 存储桶所在地域，必须字段
  };
  // 发起对 COS 的请求，进行图片审核
  cos.request({
    Bucket: config.Bucket, Region: config.Region, Method: 'GET', Key: file,  // 存储桶内的图片文件，必须字段
    Query: {
      'ci-process': 'sensitive-content-recognition', // * 固定值，必须，表示进行敏感内容识别
      'biz-type': 'e7864e636a8b11efbd6d5254000fc30f', // * 审核类型，非必须如果不填是默认的,判断的类型少
      'detect-url': '', // * 审核任意公网可访问的图片链接，非必须
      'interval': 5, // * 审核 GIF 动图时，每隔 interval 帧截取一帧，非必须
      'max-frames': 5, // * 审核 GIF 动图时，最大截帧数，非必须
      'large-image-detect': '0', // * 是否需要压缩图片后再审核，非必须
      'dataid': '123', // * 自定义图片标识，非必须
    },
  }, function (err, data) {
    if (err) {
      // 处理请求出错
      console.log(err, '失败');
    } else {
      // 处理请求成功 
      const data1 = transformData(data.RecognitionResult)
      // console.log(data1.label,11111111111111111)
      // 将英文装换为中文
      const tran = translate(data1.label)

      if (data1.score > 70) {
        translate(data1.label).then(translatedText => {
          res.send({
            status: 400,
            data: data1,
            msg: '有违规内容',
            translatedText: translatedText
          })
        }).catch(err => {
          console.log(err)
        })
      } else {

        res.send({
          status: 200,
          data: data1,
          msg: '没有违规内容'
        })
      }

    }
  });
})

// 转换函数
function transformData(data) {
  return {
    dataId: data.DataId,
    jobId: data.JobId,
    label: data.Label,
    subLabel: data.SubLabel,
    score: data.Score,
    category: data.Category,
    object: data.Object,
    state: data.State,
    Text: data.Text,
    terrorismScore: data.TerrorismInfo.Score,
  };
}

router.post('/upload1', async (req, res) => {
  let { userid } = req.query
  console.log('userid', userid);

  var Form = new multiparty.Form();
  Form.uploadDir = 'uploads'
  Form.parse(req, async function (err, fields, files) {

    let image = 'http://localhost:3000/' + files.file[0].path
    let data = await userModel.findByIdAndUpdate({ _id: userid }, { img: image });
    res.send({ code: 200, data: image })
  })
})

async function translate(data) {
  const tencentcloud = require("tencentcloud-sdk-nodejs-tmt"); // 导入对应产品模块
  const TmtClient = tencentcloud.tmt.v20180321.Client;
  const clientConfig = {
    credential: {
      secretId: "AKID43EH8kM1YwIzUvDG6lBMPq2AAvRijUDo",
      secretKey: "ThgRzIEyjOo0zmKfqqdEeqrfFblhQB1o",
    },
    region: "ap-beijing",
    profile: {
      httpProfile: {
        endpoint: "tmt.tencentcloudapi.com",
      },
    },
  };
  // 实例化要请求产品的client对象,clientProfile是可选的
  const client = new TmtClient(clientConfig);
  const params = {
    "SourceText": data,
    "Source": "en",
    "Target": "zh",
    "ProjectId": 0,
    "UntranslatedText": ""
  };

  return client.TextTranslate(params).then(
    (data) => {
      // console.log(data);
      return data.TargetText
    },
    (err) => {
      console.error("error", err);
    }
  );

}


router.get('/getding', (req, res) => {
  let data = dingModel.find()
  res.send({
    code: 200,
    data
  })
})



module.exports = router;